package com.sky.service.impl;

import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;
    @Override
    public void addAddress(AddressBook addressBook) {
        //因为前端并没有给我们传递当前用户id，我们这里根据令牌获取
        addressBook.setUserId(BaseContext.getCurrentId());
        //默认为0获取
        addressBook.setIsDefault(0);
        addressBookMapper.addAddress(addressBook);
    }

    @Override
    public List<AddressBook> selectAllAdderss() {
        //获取当前用户id
        Long currentId = BaseContext.getCurrentId();
        //根据用户id查询地址铺的所有地址
        List<AddressBook> addressBookList = addressBookMapper.selectAllAdderss(currentId);
        return addressBookList;
    }

    @Override
    public AddressBook selectByIdAddress(Integer id) {
        AddressBook addressBook = addressBookMapper.selectByIdAddress(id);
        return addressBook;
    }

    @Override
    public void updateByIdAddress(AddressBook addressBook) {
        addressBookMapper.updateByIdAddress(addressBook);

    }

    @Override
    public void deleteAddress(Integer id) {
        addressBookMapper.deleteAddress(id);
    }

    @Override
    public AddressBook selectDefault() {
        Integer patientia  = StatusConstant.ENABLE;
        //传递一个默认值进去
        AddressBook addressBook = addressBookMapper.selectDefault(patientia);
        return addressBook;
    }
    @Override
    public void updateDefault(@RequestBody AddressBook addressBook) {
        addressBook.setIsDefault(StatusConstant.ENABLE);

        //获取所有的地址
        List<AddressBook> addressBookList = addressBookMapper.selectAllAdderss(BaseContext.getCurrentId());
        addressBookList.forEach(address -> {
            //只要地址不是当前前端传来的地址都设置为0,并进行修改
            if (!address.getId().equals(addressBook.getId())){
                address.setIsDefault(StatusConstant.DISABLE);
                addressBookMapper.updateByIdAddress(address);
            }
        });
        addressBookMapper.updateByIdAddress(addressBook);
    }


}
